package app.controllers.product;

import app.Const;
import app.models.app.ProductRecommend;
import app.models.product.Product;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import goja.rapid.db.DaoKit;
import org.joda.time.DateTime;

import java.util.List;

/**
 * <p>
 * 产品推送管理
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class PushController extends Controller {

    @Before(GET.class)
    public void index(){}

    /**
     * 列表访问
     */
    @Before(GET.class)
    public void dtlist(){
        final DTCriterias criterias = DTCriterias.criteriasWithRequest(getRequest());
        renderDataTables(criterias, ProductRecommend.class);
    }

    @Before(GET.class)
    public void create() {
        ProductRecommend recommend = new ProductRecommend();
        List<Product> products = Product.dao.findAllAvailable();
        setAttr("products", products);
        setAttr("r",recommend);
        setAttr(Const.ACTION_ATTR,Const.CREATE_ACTION);
        render("item.ftl");
    }

    @Before(GET.class)
    public void edit() {
        String id = getPara(0, "0");
        ProductRecommend recommend = ProductRecommend.dao.findById(id);

        List<Product> products = Product.dao.findAllAvailable();
        setAttr("r",recommend);
        setAttr("products", products);
        setAttr(Const.ACTION_ATTR,Const.EDIT_ACTION);
        render("item.ftl");
    }

    @Before(POST.class)
    public void save() {
        String sel_product = getPara("sel_product");
        String[] split = sel_product.split("-");
        if(split.length != 2){
            return;
        }

        ProductRecommend recommend = getModel(ProductRecommend.class,"r");
        recommend.set(Const.FIELD_PRODUCT,split[0]);
        recommend.set("product_name",split[1]);

        if (DaoKit.isNew(recommend)) {
            recommend.set("recommend_time", DateTime.now().toDate());
            recommend.set("recommend_date", DateTime.now().toDate());
            recommend.save();
        } else {
            recommend.update();
        }
        redirect("/product/push");
    }


    /**
     * 删除
     */
    public void delete(){
        int id = getParaToInt(0, 0);
        boolean status = ProductRecommend.dao.deleteById(id);
        if(status){
            renderAjaxSuccess();
        }else {
            renderAjaxFailure();
        }
    }
}
